﻿#include "servernotice.h"
#include "ui_servernotice.h"

ServerNotice::ServerNotice(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ServerNotice)
{
    ui->setupUi(this);
    //关联客户端链接信号
    connect(&mserver, &QTcpServer::newConnection, this, &ServerNotice::new_client);
    //启动服务器
    if(!mserver.listen(QHostAddress::Any, 9999))
    {
        qDebug()<<"listen fail";
    }

}
ServerNotice::~ServerNotice()
{
    delete ui;
}
void ServerNotice::new_client()
{
    QTcpSocket *msocket = mserver.nextPendingConnection();
    connect(msocket, &QTcpSocket::readyRead, this, &ServerNotice::read_data);
    //插入列表中
    clients.append(msocket);
    ui->listWidget->addItem(msocket->peerAddress().toString());
}


void ServerNotice::read_data()
{
    QTcpSocket* msocket = (QTcpSocket*)sender();
    qDebug()<<msocket->readAll();
}


void ServerNotice::on_sendBt_clicked()
{
    //根据listWidget列表当前行来确定套接字
    int row = ui->listWidget->currentRow();
    QTcpSocket *msocket = clients.at(row);

    QString data = ui->textEdit->toPlainText();
    msocket->write(data.toUtf8());

}


void ServerNotice::on_cleartBt_clicked()
{
    ui->textEdit->clear();
}
